<template>
  <div class="classify app_content">
    <!-- 导航栏  titelText="新增编辑"-->
    <div class="header_body">
      <header-nav :slefBack="true" :titelText="titelText" @goBack="goBack"> </header-nav>
    </div>
    <div class="detail_body">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
              required
              v-model="itemInfo.title"
              name="标题"
              label="标题"
              placeholder="标题"
              :rules="[{ required: true, message: '请填写标题' }]"
          />
          <van-field
              required
              v-model="itemInfo.source"
              name="来源"
              label="来源"
              placeholder="来源"
              :rules="[{ required: true, message: '请填写来源' }]"
          />
          <van-field
              required
              v-model="itemInfo.author"
              name="作者"
              label="作者"
              placeholder="作者"
              :rules="[{ required: true, message: '请填写作者' }]"
          />
          <van-field required name="uploader" label="文件上传">
            <template #input>
              <van-uploader
                  v-model="itemInfo.fileList"
                  :after-read="afterRead"
                  :before-delete="deleteFile"
                  accept=".pdf,.doc,.docx"
                  :max-count="3"
                  upload-icon="add"
                    @click-preview="onPreview"
              />
<!--              <vant-uploader v-model="itemInfo.fileList" />-->
            </template>
          </van-field>
          <van-field
              required
              v-model="itemInfo.releaseTime"
              is-link
              readonly
              name="datePicker"
              label="时间选择"
              placeholder="点击选择时间"
              @click="showPickerData = true"
          />
          <van-popup v-model:show="showPickerData" destroy-on-close position="bottom">
            <van-date-picker
                :model-value="pickerValueData"
                @confirm="onConfirmData"
                @cancel="showPickerData = false"
            />
          </van-popup>
          <van-field
              required
              v-model="itemInfo.provinceCity"
              is-link
              readonly
              name="area"
              label="地区选择"
              placeholder="点击选择省市"
              @click="showArea = true"
          />
          <van-popup v-model:show="showArea" destroy-on-close position="bottom">
            <cascader
                v-model="cascaderValue"
                title="请选择"
                @close="showArea = false;"
                @finish="onFinish"/>
          </van-popup>
          <van-field
              required
              v-model="itemInfo.content"
              rows="4"
              autosize
              label="内容"
              type="textarea"
              placeholder="请输入内容"
          />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>

    </div>
  </div>
</template>
<script setup name="ItemEdit">
import {ADD_SAVE_ADVICE, UPDATE_SAVE_ADVICE} from "@/api/cooperativeOffice/serviceAdvisory.js";
import {showDialog} from "vant";
import {uploadsFile} from "@/api/cooperativeOffice/provinceCity.js";
const router = useRouter();
const itemInfo = ref({
  fileList: [],
  provinceCity: ""
})
const valFileList = ref([])
const titelText = ref("")
onMounted(() => {
  const query = router?.currentRoute?.value?.query;
  itemInfo.value = query.itemInfo ? JSON.parse(query.itemInfo) : {}
  titelText.value = itemInfo.value.adviceId ? '编辑预约信息' : '新增预约信息'
  if (!itemInfo.value.longAnnex) {
    return;
  }
  const longAnnex = itemInfo.value.longAnnex.split(",")
  if (longAnnex[0] == "") {
    return
  }
  const annex = itemInfo.value.annex
  itemInfo.value.fileList = longAnnex.map((item, index) => {
    return {
      url:item
    }
  })
  valFileList.value = annex.split(",").map((item, index) => {
    return {
      name: item,
      url:longAnnex[index] || "",
      shortUrl: item
    }
  })
  if (itemInfo.value.cityName) {
    itemInfo.value.provinceCity = itemInfo.value.cityName + itemInfo.value.districtName
  }
})
const showArea = ref(false);
const showPickerData = ref(false);
const pickerValueData = ref([]);
const onConfirmData = ({ selectedValues }) => {
  itemInfo.value.releaseTime = selectedValues.join('-');
  pickerValueData.value = selectedValues;
  showPickerData.value = false;
};
const cascaderValue = ref('');

const onFinish = ({ selectedOptions }) => {
  showArea.value = false
  cascaderValue.value = selectedOptions.map((option) => option.name).join('/');
  itemInfo.value.cityCode = selectedOptions[0].code
  itemInfo.value.cityName = selectedOptions[0].name
  itemInfo.value.districtCode = selectedOptions[1].code
  itemInfo.value.districtName = selectedOptions[1].name
  itemInfo.value.provinceCity = itemInfo.value.cityName + itemInfo.value.districtName
};
const onSubmit = async (values) => {
  const id = itemInfo.value.adviceId;
  let annex = valFileList.value.map((item) => item.shortUrl)
  let itemProject = {
    ...itemInfo.value,
    annex: annex[0] ? annex.toString(",") : ""
  }
  let res
  if (id) {
    res = await UPDATE_SAVE_ADVICE(itemProject);
  } else {
    res = await ADD_SAVE_ADVICE(itemProject);
  }
  if (res?.code == 20000) {
    showDialog({
      message: '操作成功',
    }).then(() => {
      goBack()
    });
  }
};
const goBack = () => {
  router.go(-1);
};
function onPreview(val1, detail) {
  window.open(valFileList.value[detail.index].url); //url为下载http地址
}
async function afterRead(file) {
  const res = await uploadsFile({
    file: file.file
  });
  if (res?.code == 20000) {
    valFileList.value.push({
      name: file.name,
      ...res.data[0],
    });
  }
}
function deleteFile(file, detail) {
  valFileList.value.splice(detail.index, 1)
  return true
}
</script>
<style lang="less" scoped>
.classify {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background-color: #f4f4f4;
}
</style>